﻿using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace PlusTween
{
    public class PlusTweenAlpha : PlusTweenBase
    {
        public float from = 0;
        public float to = 1;

        private CanvasGroup _canvasGroup = null;
        private CanvasGroup canvasGroup {
            get {
                if (null == _canvasGroup)
                {
                    _canvasGroup = transform.GetComponent<CanvasGroup>();
                }
                return _canvasGroup;
            }
        }

        

        private Tweener tweener;
        private float value;
        private float TweenGetter() { return value; }
        private void TweenSetter(float _value) { value = _value; if (null != canvasGroup) { canvasGroup.alpha = value; } }

        private void OnEnable()
        {
            if (isBronOrigin) { SetValueFrom(); }
        }
        private void OnDisable()
        {
            if (null != tweener) { DOTween.Kill( tweener.id ); }
        }

        public override void StartIn()
        {
            
            if (null != canvasGroup) {
                
                if (null == tweener) {
                    tweener = DOTween.To(TweenGetter, TweenSetter, to, duration);
                    tweener.SetAutoKill(false);
                    tweener.SetEase( animationCurve );
                }
                tweener.ChangeValues(from, to, duration);
                tweener.Restart( true, 0 );
                
                tweener.PlayForward();
            }

        }

        public override void StartOut()
        {
            if (null != canvasGroup)
            {
                canvasGroup.alpha = from;

                if (null == tweener)
                {
                    tweener = DOTween.To(TweenGetter, TweenSetter, to, duration);
                    tweener.SetAutoKill(false);
                    tweener.SetEase(animationCurve);
                }
                tweener.Restart(true, 1);
                tweener.PlayBackwards();
            }
        }


        public override void SetValueFrom(){ TweenSetter(from);}
        public override void SetValueTo(){  TweenSetter(to);}


    }
}
